package com.beemans.common.ui.views

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.beemans.common.ext.addOnGlobalLayoutListener

/**
 * @author tiamosu
 * @date 2021/3/15
 *
 * 描述：两道白色闪光动画
 */
class LightningImageView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {

    private var gradient: Shader? = null
    private var gradientMatrix: Matrix? = null
    private var viewWidth = 0
    private var viewHeight = 0
    private var translateX = 0f
    private var translateY = 0f
    private var isAnimating = false
    private lateinit var paint: Paint
    private lateinit var rect: Rect
    private lateinit var valueAnimator: ValueAnimator
    private var autoRun = true //是否自动运行动画

    init {
        init()
    }

    private fun init() {
        rect = Rect()
        paint = Paint()
        initGradientAnimator()
    }

    fun setAutoRun(autoRun: Boolean) {
        this.autoRun = autoRun
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        rect.set(0, 0, width, height)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        if (viewWidth == 0) {
            viewWidth = width
            viewHeight = height
            if (viewWidth > 0) {
                //亮光闪过
                gradient = LinearGradient(
                    0f,
                    0f,
                    viewWidth / 2f,
                    viewHeight.toFloat(),
                    intArrayOf(0x00ffffff, 0x73ffffff, 0x00ffffff, -0x66000001, 0x00ffffff),
                    floatArrayOf(0.2f, 0.35f, 0.6f, 0.7f, 1f),
                    Shader.TileMode.CLAMP
                )
                paint.shader = gradient
                paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.LIGHTEN)

                gradientMatrix = Matrix().apply {
                    setTranslate(-2f * viewWidth, viewHeight.toFloat())
                }
                gradient?.setLocalMatrix(gradientMatrix)
                rect.set(0, 0, w, h)
            }
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (isAnimating && gradientMatrix != null) {
            canvas.drawRect(rect, paint)
        }
    }

    private fun initGradientAnimator() {
        valueAnimator = ValueAnimator.ofFloat(0f, 1f)
        valueAnimator.duration = 1500
        valueAnimator.addUpdateListener { animation ->
            val v = animation.animatedValue as Float
            //❶ 改变每次动画的平移x、y值，范围是[-2mViewWidth, 2mViewWidth]
            translateX = 4 * viewWidth * v - viewWidth * 2
            translateY = viewHeight * v
            //❷ 平移matrix, 设置平移量
            gradientMatrix?.setTranslate(translateX, translateY)
            //❸ 设置线性变化的matrix
            gradient?.setLocalMatrix(gradientMatrix)
            //❹ 重绘
            invalidate()
        }

        if (autoRun) {
            valueAnimator.repeatCount = ValueAnimator.INFINITE
            addOnGlobalLayoutListener {
                isAnimating = true
                valueAnimator.start()
            }
        }
    }

    //停止动画
    fun stopAnimation() {
        if (isAnimating) {
            isAnimating = false
            valueAnimator.cancel()
            invalidate()
        }
    }

    //开始动画
    fun startAnimation() {
        if (!isAnimating) {
            isAnimating = true
            valueAnimator.start()
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        if (valueAnimator.isRunning) {
            valueAnimator.end()
        }
    }
}